import "./index.less";
import Header from "@/components/header";
import { useState, useCallback, useEffect } from "react";
import { SearchBar, InfiniteScroll, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { useLocalStorageState } from "ahooks";

import Button from "../../components/button";
import Footer from "../../components/footer";
import CustomModal from "../../components/customModal";
import { getOrderList } from "@/api/orders";
import { LOCAL_APP_INFO } from "@/utils/const";

const size = 5; // 每页加载数量

function Orders() {
  const navigate = useNavigate();
  const [searchInput, setSearchInput] = useState("");
  const [orders, setOrders] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [current, setCurrent] = useState(1);
  const [currentOrder, setCurrentOrder] = useState({});
  const [visible, setVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // 获取订单数据
  const getOrderListData = async (page = current) => {
    if (isLoading) return;

    setIsLoading(true);
    try {
      const res = await getOrderList({
        current: page,
        size,
        keyword: searchInput || undefined, // 使用正确的搜索参数
      });

      const { data } = res;
      const { records, current: currentPage, pages } = data;
      if (currentPage === 1) {
        setOrders(records);
      } else {
        setOrders((prev) => [...prev, ...records]);
      }

      setCurrent(currentPage + 1);

      // 判断是否还有更多数据
      if (currentPage >= pages) {
        setHasMore(false);
      } else {
        setHasMore(true);
      }
    } catch (error) {
      Toast.show({
        content: "获取订单数据失败，请重试",
        duration: 2000,
        maskClickable: false,
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 加载更多订单数据
  const loadMore = useCallback(async () => {
    if (!isLoading) {
      await getOrderListData(current);
    }
  }, [current, isLoading, searchInput]);

  const handleDelete = (orderId) => {
    setOrders((prev) => prev.filter((o) => o.id !== currentOrder.id));
    setVisible(false);
  };

  // 搜索处理
  const handleSearch = (val) => {
    setSearchInput(val);
    setCurrent(1);
    setHasMore(true);
    getOrderListData(1);
  };

  // 清空搜索
  const handleClearSearch = () => {
    setSearchInput("");
    setCurrent(1);
    setHasMore(true);
    getOrderListData(1);
  };

  // 初始化加载
  useEffect(() => {
    getOrderListData(1);
  }, []);

  const statusMap = {
    1: "支付成功",
  };

  return (
    <div className="orders-page">
      <Header />
      <div className="orders-content">
        <div className="orders-top">
          <SearchBar
            placeholder="输入商户名称"
            value={searchInput}
            autoFocus
            style={{
              "--border-radius": "100px",
            }}
            onChange={setSearchInput}
            onSearch={handleSearch}
            onClear={handleClearSearch}
            onCancel={handleClearSearch}
          />
        </div>

        <div className="orders-scroll">
          <div className="order-list">
            {isLoading && orders.length === 0 ? (
              <div className="loading-container">
                <div className="loading-text">正在加载订单...</div>
              </div>
            ) : orders.length === 0 ? (
              <div className="empty-container">
                <div className="empty-text">暂无订单记录</div>
                <div className="empty-tip">快去消费享受优惠吧~</div>
              </div>
            ) : (
              orders.map((o) => (
                <div key={o.id} className="order-card">
                  <div className="order-info">
                    <div className="order-title-row">
                      <div className="order-left">
                        <div className="order-merchant">
                          {o.sellerName || "--"}
                        </div>
                      </div>
                      <div className="order-price-block">
                        <div className="order-amount">¥ {o.orderAmt}</div>
                        <div className="order-discount">
                          已减优惠{Number(o.pointDeductAmt || 0).toFixed(2)}  元
                        </div>
                      </div>
                    </div>
                    <div className="order-meta order-no">
                      订单编号：{o.orderId || o.orderNo}
                    </div>

                    <div className="order-meta order-no ">
                      订单状态：<span className="order-tabs">{statusMap[o.orderStatus] || "取消订单"}</span>
                    </div>
                    <div className="order-meta order-no ">
                      订单类型：<span className="order-tabs">{o.orderType}</span>
                    </div>
                    {o.refundMoney ? (
                      <div className="order-meta order-no">
                        退款金额：<span className="order-tabs">¥ {o.refundMoney}</span>
                      </div>
                     ) : null}
                    <div className="order-meta">交易时间：{o.orderTime}</div>
                    <div className="order-meta">地址：{o.address || "--"}</div>
                    {/* <div className="order-actions">
                      <button
                        className="order-delete"
                        onClick={(e) => {
                          setCurrentOrder(o);
                          setVisible(true);
                        }}
                      >
                        删除订单
                      </button>
                    </div> */}
                  </div>
                </div>
              ))
            )}

            {orders.length > 0 && (
              <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                {hasMore ? (
                  <div className="loading-text">加载中...</div>
                ) : (
                  <div className="no-more-text">没有更多了</div>
                )}
              </InfiniteScroll>
            )}
          </div>
        </div>
      </div>
      <Footer>
        <div className="footer-button">
          <Button type="primary" block onClick={() => navigate("/statistics")}>
            轻按查看月/年度省钱账单
          </Button>
        </div>
      </Footer>

      <CustomModal
        title="是否确认删除"
        message="请仔细核对是否要删除该条记录？"
        visible={visible}
        mode={"confirm"}
        position={"center"}
        onConfirm={() => {
          handleDelete(currentOrder.id);
        }}
        onCancel={() => {
          setVisible(false);
        }}
      />
    </div>
  );
}

export default Orders;
